package com.ds.iot.cmd;

import com.alibaba.fastjson.JSONObject;
import com.ds.command.Command;
import com.ds.command.IRLearnCommand;
import com.ds.common.JDSException;
import com.ds.common.cache.Cache;
import com.ds.common.cache.CacheManagerFactory;
import com.ds.config.ErrorResultModel;
import com.ds.config.ResultModel;
import com.ds.enums.CommandEnums;
import com.ds.enums.CommandEventEnums;
import com.ds.home.client.CommandClient;
import com.ds.iot.DeviceEndPoint;
import com.ds.iot.ct.CtIotFactory;
import com.ds.iot.device.XUIHAParam;
import com.ds.msg.CommandMsg;
import com.ds.msg.MsgClient;
import com.ds.msg.MsgFactroy;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("/iot/cmd")
public class IotCmdService {


    @RequestMapping(value = {"/addLockCmd"}, method = {RequestMethod.GET, RequestMethod.POST})
    public @ResponseBody
    ResultModel<Command> addLockCmd(String gwieee, String ieee) {
        ResultModel<Command> result = new ResultModel<Command>();

        List<XUIHAParam> modules = new ArrayList<XUIHAParam>();
        CommandClient commandClient = CtIotFactory.getCommandClient(gwieee);
        CommandClient client = CtIotFactory.getCommandClient(gwieee);
        try {
            if (client != null) {
                Command command = commandClient.sendAddSensorCommand(ieee, 30).get();
                result.setData(command);
            } else {
                result = new ErrorResultModel();
                ((ErrorResultModel) result).setErrcode(JDSException.APPLICATIONNOTFOUNDERROR);
                ((ErrorResultModel) result).setErrdes("网关离线！");
            }

        } catch (Exception e) {
            result = new ErrorResultModel<>();
            // ((ErrorResultModel) result).setErrcode(e.getErrorCode());
            ((ErrorResultModel) result).setErrdes(e.getMessage());
        }


        return result;
    }

    @RequestMapping(value = {"/removeSensor"}, method = {RequestMethod.GET, RequestMethod.POST})
    public @ResponseBody
    ResultModel<Command> removeSensor(String gwieee, String ieee) {
        ResultModel<Command> result = new ResultModel<Command>();

        List<XUIHAParam> modules = new ArrayList<XUIHAParam>();
        CommandClient commandClient = CtIotFactory.getCommandClient(gwieee);
        CommandClient client = CtIotFactory.getCommandClient(gwieee);
        try {
            if (client != null) {
                DeviceEndPoint deviceEndPoint=CtIotFactory.getCtIotService().getEndPointByIeee(ieee);
                Command command = commandClient.sendRemoveSensorCommand(deviceEndPoint.getDevice().getSerialno(), deviceEndPoint.getSensortype().getType()).get();
                result.setData(command);
            } else {
                result = new ErrorResultModel();
                ((ErrorResultModel) result).setErrcode(JDSException.APPLICATIONNOTFOUNDERROR);
                ((ErrorResultModel) result).setErrdes("网关离线！");
            }

        } catch (Exception e) {
            result = new ErrorResultModel<>();
            // ((ErrorResultModel) result).setErrcode(e.getErrorCode());
            ((ErrorResultModel) result).setErrdes(e.getMessage());
        }


        return result;
    }


    @RequestMapping(value = {"/sendCommand"}, method = {RequestMethod.GET, RequestMethod.POST})
    public @ResponseBody
    ResultModel<Command> sendCommand(String gwieee, String commandStr) {

        JSONObject commandObj = JSONObject.parseObject(commandStr);
        ResultModel<Command> result = new ResultModel<Command>();
        if (commandObj.get("command") != null) {
            String command = commandObj.get("command").toString();
            Command jdscommand = (Command) JSONObject.parseObject(commandStr, CommandEnums.fromByName(command).getCommand());
            try {
                CommandClient client = CtIotFactory.getCommandClient(gwieee);
                if (client != null) {
                    Future<Command> commandFuture = CtIotFactory.getCommandClient(gwieee).sendCommand(jdscommand, 0);
                    Command resultCommand = commandFuture.get(2000, TimeUnit.MILLISECONDS);
                    result.setData(resultCommand);
                } else {
                    result = new ErrorResultModel();
                    ((ErrorResultModel) result).setErrcode(JDSException.APPLICATIONNOTFOUNDERROR);
                    ((ErrorResultModel) result).setErrdes("网关离线！");
                }

            } catch (Exception e) {
                e.printStackTrace();
                result = new ErrorResultModel();
                ((ErrorResultModel) result).setErrcode(JDSException.APPLICATIONNOTFOUNDERROR);
                ((ErrorResultModel) result).setErrdes(e.getMessage());
            }
        }


        return result;
    }


    @RequestMapping(value = {"/getCommandStatus"}, method = {RequestMethod.GET, RequestMethod.POST})
    public @ResponseBody
    ResultModel<Command> getCommandStatus(String commandId, Integer code) {
        ResultModel<Command> result = new ResultModel<Command>();
        if (commandId != null && !commandId.equals("")) {
            MsgClient<CommandMsg> client = MsgFactroy.getInstance().getClient(null, CommandMsg.class);
            CommandMsg commandMsg = client.getMsgById(commandId);
            final JSONObject jsonobj = JSONObject.parseObject(commandMsg.getBody());
            final Command command = (Command) JSONObject.parseObject(commandMsg.getBody(), CommandEnums.fromByName(jsonobj.getString("command")).getCommand());
            command.setCommandId(commandId);
            command.setResultCode(commandMsg.getResultCode());

            Cache irCache = CacheManagerFactory.createCache("JDS", "irCache");

            if ((command instanceof IRLearnCommand) && command.getResultCode().equals(CommandEventEnums.COMMANDSENDSUCCESS)) {

                irCache.put(command.getGatewayieee() + "||" + code, ((IRLearnCommand) command).getModeId());
            }

            result.setData(command);
        }


        return result;

    }


}
